import React, { Component, ReactNode } from "react";
import { View, Map, Button } from "@tarojs/components";
import "./index.scss";
import { AtButton, AtNavBar } from "taro-ui";
import AMapLoader from "@amap/amap-jsapi-loader";
import Taro from "@tarojs/taro";
import { isEmpty } from "../../utils/kit";
export default class DrawArea extends Component {
  state = {
    startDraw: false,
    drawing: false,
  };
  mapCtx: any = null;
  drawing = false;
  mapRef = React.createRef();
  componentDidMount(): void {
    const { lat, lng, location } = Taro.getStorageSync("areaProps");
    if (!isEmpty(lat) && !isEmpty(lng)) {
      let _location = null;
      if (!isEmpty(location)) {
        if (typeof location === "string") {
          _location = JSON.parse(location);
        } else {
          _location = location;
        }
      }
      this.initMap({
        lat,
        lng,
        location:_location
      });
    } else {
      this.initMap({});
    }
  }
  initMap = ({
    lng = 120.63679638040358,
    lat = 30.791165588900505,
    location = null,
  }) => {
    let _this = this;
    AMapLoader.load({
      key: "25d7453509c754af661a6efbdf5623d2", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    }).then((AMap) => {
      this.mapCtx = new AMap.Map("map", {
        zoom: 15,
        center: [lng, lat],
        doubleClickZoom: false,
        dragEnable: true,
        zoomEnable: true,
      });
      let path: any[] = [];
      let drawing = false;
      let polygon: any = null;

      if(location){
        polygon = new AMap.Polygon({
          path: location,
          strokeColor: "#80d8ff",
          fillColor: "#00b0ff",
          map:this.mapCtx
        });
      }
      this.mapCtx.on("touchstart", function (e: any) {
        if (!_this.state.startDraw) return;
        drawing = true;
        polygon = null;
        path = [];
        const lnglat = e.lnglat;
        path.push([lnglat.lng, lnglat.lat]);
      });

      this.mapCtx.on("touchmove", function (e) {
        if (!_this.state.startDraw) return;
        if (!drawing) return;
        const lnglat = e.lnglat;
        path.push([lnglat.lng, lnglat.lat]);
        if (polygon) {
          polygon.setPath(path);
        } else {
          polygon = new AMap.Polygon({
            path: path,
            strokeColor: "#80d8ff",
            strokeWeight: 2,
            fillColor: "#00b0ff",
            fillOpacity: 0.4,
            map: _this.mapCtx,
          });
        }
      });
      this.mapCtx.on("touchend", function (e) {
        if (!_this.state.startDraw) return;
        drawing = false;
        if (path.length > 2) {
          path.push(path[0]);
          polygon.setPath(path);
          path = [];
        }
      });
    });
  };
  render(): ReactNode {
    const {  startDraw } = this.state;
    return (
      <View className="da-container">
        <AtNavBar
          onClickLeftIcon={() => {
            Taro.navigateBack();
          }}
          leftIconType="chevron-left"
          leftText="返回"
          color="#3051BE"
          rightFirstIconType="check"
          onClickRgIconSt={() => {
            if (this.mapCtx) {
              let paths = this.mapCtx.getAllOverlays();
              if (paths.length === 0) {
                Taro.showToast({
                  title: "请框选范围！",
                  icon: "none",
                  duration: 2000,
                });
                return;
              }
              let path = paths[0].getPath();
              Taro.setStorageSync("areaProps", {
                location: path.map((p) => [p.lng, p.lat]),
              });

              Taro.navigateBack();
            }
          }}
        >
          <View>区域框选</View>
        </AtNavBar>
        <View
          id="map"
          className="map-container"
          
        ></View>
        <View
          className="area-bottom-btn"
          style={{
            padding: "10px 20px",
          }}
        >
          <AtButton
            size="small"
            disabled={startDraw}
            onClick={() => {
              this.setState(
                {
                  startDraw: true,
                },
                () => {
                  this.mapCtx.setStatus({
                    dragEnable: false,
                    zoomEnable: false,
                  });
                }
              );
            }}
          >
            开始绘制
          </AtButton>
          <AtButton
            size="small"
            style={{
              marginTop: "10px",
            }}
            onClick={() => {
              if (this.mapCtx) {
                this.mapCtx.getAllOverlays().forEach((overlay) => {
                  this.mapCtx.remove(overlay);
                });
                this.mapCtx.setStatus({
                  dragEnable: true,
                  zoomEnable: true,
                });
                this.setState({
                  startDraw: false,
                  drawing: false,
                });
              }
            }}
          >
            清除绘制
          </AtButton>
        </View>
        {/* <View
          style={{
            width: "100vw",
            height: "100vh",
          }}
        >
          <Map
            ref={this.mapRef}
            longitude={116.397428}
            latitude={39.90923}
            scale={14}
            polygons={polygons}
            enableScroll={false}
            onError={() => {}}
            style={{ width: "100%", height: "100%" }}
          />
        </View> */}
      </View>
    );
  }
}
